package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.RoleMenu;
import com.taotao.rop.response.BaseResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping(value = "/rolemenu")
public class RoleMenuController {
    @RequestMapping(value = "/list/{roleId}", method = RequestMethod.POST)
    @ResponseBody
    public Object listRoleMenu(HttpServletRequest request, @PathVariable String roleId) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(Long.parseLong(roleId));
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(roleMenu, BaseResponse.class, "roleMenu.list", "1.0");
        if (response.isSuccessful()) {
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/insert/{roleId}", method = RequestMethod.POST)
    @ResponseBody
    public Object insertRoleMenu(HttpServletRequest request, @PathVariable String roleId) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String[] menuIds = request.getParameter("menuIds").split(",");

        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(Long.parseLong(roleId));

        boolean batchInsertSuccess = true;
        //删除之前权限
        CompositeResponse<BaseResponse> responseRemove = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(roleMenu, BaseResponse.class, "roleMenu.remove", "1.0");
        if (!responseRemove.isSuccessful()) {
            batchInsertSuccess = false;
        } else {
            //重新赋予权限
            for (String menuId : menuIds) {
                roleMenu.setMenuId(Long.parseLong(menuId));
                CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                        .post(roleMenu, BaseResponse.class, "roleMenu.insert", "1.0");
                if (!response.isSuccessful()) {
                    batchInsertSuccess = false;
                    break;
                }
            }
        }

        BaseResponse response = new BaseResponse();
        response.setSuccess(batchInsertSuccess);
        return response;
    }
}
